//'use strict';
/**
 * Required
 */
//@import PhonemapUtil

//Private Mode

var userId = 0;

/**
 * Constructor.
 */
function PhonemapLogin() {
}

/**
 * Inserts facebook User.
 */
PhonemapLogin.insertFacebookUser = function(curPos) {
	console.log('Welcome!  Fetching your information.... ');
	FB.api('/me', function(response) {
		if (response != null) {
			// making the ajax call
			userId = response.id;
			PhonemapGlobal.setUserId(userId);
			$.ajax({
				url : "/login?action=getUser&id=" + userId,
				type: 'GET',
		        data: '',
				success : function(resp) {
					if (resp != null) {
						// getting the data from the response object
						var data = resp.data;
						if(data.length > 0) {
							if (isMobile.any()) {
								if (data[0].located_time != 'null') {
									var user = data[0];
									var oldPos = PhonemapUtil.getLatLng(user.located);
									var dist = PhonemapUtil.distance(oldPos.lat(), oldPos.lng(), curPos.lat(), curPos.lng(), 'K');
									if (dist > 0.5) {
										updateUser(response, curPos);
									} else {
										goFollow(userId);
									}
									
								} else {
									updateUser(response, curPos);
								}
							} else {
								goFollow(userId);
							}
							
						} else {
							// Insert new user into database
							if (isMobile.any()) {
								insertUser(response, curPos);
							} else {
								document.getElementById('status').innerHTML = 'You have to login via phone for the first time.';
							}
						}
						
					} else {
						document.getElementById('status').innerHTML = 'Your Id does not exist in phonemap, please try it again.';
					}
				},
				error : function(resp){
					document.getElementById('status').innerHTML = 'Cannot get data! Please check again';
				}
			});
			
		} else {
			//alert('Your Id does not exist in facebook, please try it again.');
			document.getElementById('status').innerHTML = 'Your Id does not exist in facebook, please try it again.';
		}

	});
};

/**
 * Updates position.
 * @param userId {String}
 * @param pos {google.maps.LatLng}
 */
PhonemapLogin.updatePosition = function(pos, page) {
	var userId = PhonemapGlobal.getUserId();
	var oldPos = PhonemapGlobal.getCurPos();
	alert('update position');
	if (userId == null || oldPos == null) {
		PhonemapUtil.goHome();
	}
	var dist = PhonemapConstant.MAX_DISTANCE;
	if (oldPos != null) {
		dist = PhonemapUtil.distance(oldPos.lat(), oldPos.lng(), pos.lat(), pos.lng(), 'K');
	}
	
	if (dist > PhonemapConstant.MAX_DISTANCE) {
		var timezone = PhonemapGlobal.getTimezone();
		var located_time = PhonemapUtil.calculateTime(timezone);
		var URLString = '&id=' + userId + '&latitude='
						+ pos.lat() + '&longitude=' + pos.lng() + '&located_time='
						+ located_time;
		$.ajax({
			url : "/user?action=UPDATEPOSITION"+urlString,
			type : "POST",
			data : userId,
			success : function(data) {
				if (data == null) {
					PhonemapUtil.goHome();
					PhonemapGlobal.setUserId(PhonemapConstant.STRING_EMPTY);
					PhonemapGlobal.setCurPos(PhonemapConstant.STRING_EMPTY);
				} else {
					PhonemapGlobal.setCurPos(pos);
					PhonemapUtil.goApp(page);
				}
			},
			error : function(resp) {
				PhonemapUtil.goHome();
				PhonemapGlobal.setUserId(PhonemapConstant.STRING_EMPTY);
				PhonemapGlobal.setCurPos(PhonemapConstant.STRING_EMPTY);
			}
		});
	} else {
		PhonemapUtil.goApp(page);
	}
}

/**
 * Log out.
 */
PhonemapLogin.logout = function() {
	FB.logout(function(response) {
		goLogin();
	});
}

var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function() {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function() {
        return navigator.userAgent.match(/IEMobile/i);
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
};

/**
 * Goes home.
 */
function clearCookie() {
	$("#loginstatus").css("display", "block");
	$.cookie('useraccount', '', {
		expires : 14
	});
	
}

/**
 * Go Login.
 */
function goLogin() {
	clearCookie();
	document.location.href = '/login.html';
}

/**
 * Go Follow Page.
 * @param userId
 */
function goFollow(userId) {
	$.cookie('useraccount', userId, {
		expires : 14
	});
	document.location.href = '/apps/follows.html';
}

/**
 * Go Error.
 */
function goError() {
	clearCookie();
	document.location.href = '/error.html';
}

/**
 * Parse URL.
 * @param user
 */
function parseURL(user, curPos) {
//	  "id": "40512085", 
//	  "name": "Haley Rae", 
//	  "first_name": "Haley", 
//	  "last_name": "Rae", 
//	  "link": "https://www.facebook.com/haley.halford1", 
//	  "gender": "female", 
//	  "locale": "en_US", 
//	  "updated_time": "2013-12-26T22:30:15+0000", 
//	  "username": "haley.halford1"
	var located_time = PhonemapUtil.calculateTime(user.timezone);
	//var curPos = PhonemapGlobal.getCurPos();
	var urlString = '&id=' + user.id + '&fullname=' + user.name + '&link='
			+ user.link + '&birthday=' + user.birthday + '&interested_in='
			+ user.interested_in + '&gender=' + user.gender
			+ '&relationship_status=' + user.relationship_status + '&timezone='
			+ user.timezone + '&gender=' + user.gender + '&verified='
			+ user.verified + '&email=' + user.email + '&updated_time='
			+ user.updated_time + '&locale=' + user.locale + '&phone='
			+ user.phone + '&username=' + user.username + '&latitude='
			+ curPos.lat() + '&longitude=' + curPos.lng() + '&located_time='
			+ located_time;
	return urlString;
}

/**
 * Updates user.
 * @param user
 */
function updateUser(user, curPos) {
	console.log('Updating user into system...');
	var urlString = parseURL(user, curPos);
	$.ajax({
		url : "/user?action=UPDATE"+urlString,
		type : "POST",
		data:user.id,
		success : function(data) {
			if (data == null) {
				document.getElementById('status').innerHTML = 'Update process has error.';
				PhonemapGlobal.setUserId(PhonemapConstant.STRING_EMPTY);
				PhonemapGlobal.setCurPos(PhonemapConstant.STRING_EMPTY);
			} else {
				PhonemapGlobal.setUserId(user.userId);
				PhonemapGlobal.setCurPos(curPos);
				goFollow(userId);
			}
		},
		error : function(resp) {
			document.getElementById('status').innerHTML = 'Cannot update your info. please try it again!';
			PhonemapGlobal.setUserId(PhonemapConstant.STRING_EMPTY);
			PhonemapGlobal.setCurPos(PhonemapConstant.STRING_EMPTY);
		}
	});

}

/**
 * Inserts user.
 * @param user
 */
var insertUser = function(user, curPos) {
	console.log('Inserting user into system...');
	var urlString = parseURL(user, curPos);
	$.ajax({
		url : "/user?action=INSERT"+urlString,
		type : "POST",
		data:user.id,
		success : function(data) {
			if (data == null) {
				document.getElementById('status').innerHTML = 'Insert process has error.';
			} else {
				alert("Thanks for join in us.");
				goFollow(userId);
			}
		},
		error : function(resp) {
			alert("Fail!");
			document.getElementById('status').innerHTML = 'Cannot insert your info. please try it again!';
		}
	});

}




